import { IStrategyOptions, Strategy } from "passport-local"
import { PassportStrategy } from "@nestjs/passport"
import { InjectRepository } from "@nestjs/typeorm"
import { UserDemo } from "src/Entities/UserDemo/UserDemo.dao"
import { Repository } from "typeorm"
import { BadRequestException, Injectable } from "@nestjs/common"
import { compareSync } from "bcryptjs"

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {

    constructor(@InjectRepository(UserDemo) private userDemo: Repository<UserDemo>) {
        super({
            usernameField: "username",
            passwordField: "password"
        } as IStrategyOptions)
    }

    //  验证逻辑
    async validate(username: string, password: string) {
        const user = await this.userDemo.findOne({ select: ["username", "password"], where: { username } })
        if (!user) {
            throw new BadRequestException("用户名不正确")
        }
        if (!compareSync(password, user.password)) {
            throw new BadRequestException("密码不正确")
        }
        delete user["password"]
        return user
    }

}